package com.mediocre.eg3publishsubscribe;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

public class EmitLog {

    private final static String EXCHANGE_NAME = "logs";

    public static void main(String[] args) throws IOException, TimeoutException {

        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost");

        try (Connection connection = connectionFactory.newConnection();
             Channel channel = connection.createChannel();) {

            // after establishing the connection we declared the exchange. This step is necessary as publishing to a non-existing exchange is forbidden.
            channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
            String message = args.length < 1 ? "info: Hello World!" : String.join(" ", args);

            // durable：默认false；exclusive：默认true；autoDelete：默认true；arguments：默认为null
            // channel.queueDeclare(queueName: "", durable: false, exclusive: true, autoDelete: true, arguments: null);
            // props: MessageProperties.PERSISTENT_TEXT_PLAIN，表示在rabbitmq-server退出/重启后，消息仍然保存
            channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes(StandardCharsets.UTF_8));
            System.out.println("[x] Sent '" + message + "'");
        }
    }
}
